package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.exception.BusinessException;
import com.example.entity.emp.SysDept;
import com.example.mapper.emp.SysDeptMapper;
import com.example.service.SysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 部门服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public List<SysDept> getDeptTree() {
        return baseMapper.selectDeptTree();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysDept dept) {
        // 检查部门名称是否重复
        long count = count(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getDeptName, dept.getDeptName())
                .eq(dept.getParentId() != null, SysDept::getParentId, dept.getParentId()));
        
        if (count > 0) {
            throw new BusinessException("部门名称已存在");
        }
        
        // 设置默认值
        dept.setStatus(1);
        if (dept.getSort() == null) {
            dept.setSort(0);
        }
        
        save(dept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDept dept) {
        // 检查部门名称是否重复
        long count = count(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getDeptName, dept.getDeptName())
                .eq(dept.getParentId() != null, SysDept::getParentId, dept.getParentId())
                .ne(SysDept::getId, dept.getId()));
        
        if (count > 0) {
            throw new BusinessException("部门名称已存在");
        }
        
        // 检查是否修改了上级部门，避免形成循环
        if (dept.getParentId() != null && dept.getParentId() > 0) {
            // 不能将自己设为自己的父部门
            if (dept.getParentId().equals(dept.getId())) {
                throw new BusinessException("上级部门不能选择自己");
            }
            
            // 不能将自己设为自己子部门的父部门
            List<Long> childIds = getChildrenIds(dept.getId());
            if (childIds.contains(dept.getParentId())) {
                throw new BusinessException("上级部门不能是自己的子部门");
            }
        }
        
        updateById(dept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 检查是否有子部门
        Integer count = baseMapper.hasChildren(id);
        if (count > 0) {
            throw new BusinessException("请先删除子部门");
        }
        
        // 检查部门下是否有用户
        // 实际业务中需要添加员工-部门关联检查
        
        removeById(id);
    }

    @Override
    public List<Long> getChildrenIds(Long deptId) {
        return baseMapper.selectChildrenIds(deptId);
    }
} 